#!/usr/bin/env python3
"""
智能客服系统演示
展示如何使用新增的智能客服功能
"""

import sys
import os
import json
from datetime import datetime

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from assistant.tools import (
    analyze_customer_sentiment,
    categorize_customer_query,
    handle_order_inquiry,
    generate_faq_response,
    escalate_to_human_agent,
    provide_contact_info,
    suggest_similar_products,
    track_customer_satisfaction,
    generate_smart_reply_suggestions,
    CustomerServiceSession
)


def demo_sentiment_analysis():
    """演示情绪分析功能"""
    print("=== 客户情绪分析演示 ===")
    
    test_messages = [
        "您好，我对购买的商品非常满意，质量很好！",
        "这个产品质量太差了，我要投诉！",
        "请问这个商品什么时候能发货？",
        "谢谢客服的耐心解答，服务很棒！",
        "订单迟迟不发货，我很生气！"
    ]
    
    for message in test_messages:
        result = analyze_customer_sentiment(message)
        print(f"消息: {message}")
        print(f"情绪: {result['sentiment']} (置信度: {result['confidence']:.2f})")
        print("-" * 50)


def demo_query_categorization():
    """演示查询分类功能"""
    print("\n=== 客户查询分类演示 ===")
    
    test_queries = [
        "我想查询我的订单状态",
        "这个手机的电池续航怎么样？",
        "支付失败了怎么办？",
        "我要申请退货",
        "忘记密码了，怎么重置？",
        "客服电话是多少？"
    ]
    
    for query in test_queries:
        result = categorize_customer_query(query)
        print(f"查询: {query}")
        print(f"分类: {result['primary_category']} (置信度: {result['confidence']:.2f})")
        print(f"所有匹配分类: {', '.join(result['categories'])}")
        print("-" * 50)



def demo_order_inquiry():
    """演示订单查询功能"""
    print("\n=== 订单查询演示 ===")
    
    # 测试有效订单号
    result1 = handle_order_inquiry("2024070300001")
    print(f"查询订单 2024070300001:")
    print(json.dumps(result1, ensure_ascii=False, indent=2))
    
    # 测试无效订单号
    result2 = handle_order_inquiry("9999999999999")
    print(f"\n查询无效订单号:")
    print(json.dumps(result2, ensure_ascii=False, indent=2))


def demo_faq_responses():
    """演示常见问题回答功能"""
    print("\n=== 常见问题回答演示 ===")
    
    test_questions = [
        "如何退货？",
        "配送需要多长时间？",
        "支付安全吗？",
        "会员有什么权益？",
        "可以开发票吗？",
        "这是一个不常见的问题"
    ]
    
    for question in test_questions:
        response = generate_faq_response(question)
        print(f"问题: {question}")
        if response:
            print(f"回答: {response}")
        else:
            print("回答: 未找到相关FAQ，建议转接人工客服")
        print("-" * 50)


def demo_smart_reply_suggestions():
    """演示智能回复建议功能"""
    print("\n=== 智能回复建议演示 ===")
    
    test_messages = [
        "产品质量有问题，我要投诉！",
        "谢谢你们的服务，非常满意！",
        "我想查询订单状态",
        "这个商品怎么使用？",
        "我要申请售后服务"
    ]
    
    for message in test_messages:
        suggestions = generate_smart_reply_suggestions(message)
        print(f"客户消息: {message}")
        print("建议回复:")
        for i, suggestion in enumerate(suggestions, 1):
            print(f"  {i}. {suggestion}")
        print("-" * 50)


def demo_customer_service_session():
    """演示客服会话管理功能"""
    print("\n=== 客服会话管理演示 ===")
    
    # 创建客服会话
    session = CustomerServiceSession("CS_20240703_001")
    
    # 模拟客服对话
    conversation = [
        ("customer", "你好，我想查询订单状态"),
        ("agent", "您好！请提供您的订单号，我来帮您查询。"),
        ("customer", "订单号是2024070300001"),
        ("agent", "好的，我查到您的订单已经发货，预计明天送达。"),
        ("customer", "太好了，谢谢！"),
        ("agent", "不客气！还有什么需要帮助的吗？")
    ]
    
    # 添加对话消息
    for sender, message in conversation:
        session.add_message(message, sender)
    
    # 添加满意度评价
    session.satisfaction_rating = 5
    
    # 获取会话摘要
    summary = session.get_session_summary()
    print("会话摘要:")
    print(json.dumps(summary, ensure_ascii=False, indent=2))
    
    print("\n对话历史:")
    for msg in session.messages:
        print(f"[{msg['sender']}] {msg['content']}")
        if msg['sentiment']:
            print(f"  情绪: {msg['sentiment']['sentiment']}")


def demo_product_suggestions():
    """演示产品推荐功能"""
    print("\n=== 产品推荐演示 ===")
    
    test_products = ["手机", "电脑", "耳机", "未知产品"]
    
    for product in test_products:
        suggestions = suggest_similar_products(product)
        print(f"查询产品: {product}")
        print("推荐商品:")
        for suggestion in suggestions:
            print(f"  - {suggestion['name']}: ¥{suggestion['price']} (评分: {suggestion['rating']})")
        print("-" * 50)


def demo_contact_info():
    """演示联系方式功能"""
    print("\n=== 联系方式信息演示 ===")
    
    contact_info = provide_contact_info()
    print("客服联系方式:")
    print(json.dumps(contact_info, ensure_ascii=False, indent=2))


def demo_satisfaction_tracking():
    """演示满意度跟踪功能"""
    print("\n=== 满意度跟踪演示 ===")
    
    # 测试不同评分
    ratings = [
        (5, "服务很好，解决了我的问题"),
        (3, "还可以，但响应速度有点慢"),
        (1, "很不满意，问题没有得到解决"),
        (6, "")  # 无效评分
    ]
    
    for rating, feedback in ratings:
        result = track_customer_satisfaction(rating, feedback)
        print(f"评分: {rating}, 反馈: {feedback}")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        print("-" * 30)


def demo_escalation():
    """演示转接人工客服功能"""
    print("\n=== 转接人工客服演示 ===")
    
    customer_info = {
        "customer_id": "C123456",
        "name": "张三",
        "phone": "138****8888",
        "vip_level": "金卡会员"
    }
    
    result = escalate_to_human_agent("商品质量问题需要退货", customer_info)
    print("转接结果:")
    print(json.dumps(result, ensure_ascii=False, indent=2))


def main():
    """主演示函数"""
    print("智能客服系统功能演示")
    print("=" * 60)
    
    # 运行所有演示
    demo_sentiment_analysis()
    demo_query_categorization()
    demo_order_inquiry()
    demo_faq_responses()
    demo_smart_reply_suggestions()
    demo_customer_service_session()
    demo_product_suggestions()
    demo_contact_info()
    demo_satisfaction_tracking()
    demo_escalation()
    
    print("\n演示完成！")


if __name__ == "__main__":
    main()
